package com.bootcamp.s3_1013.database.utils;

import java.io.*;
import java.sql.*;
import java.util.Properties;

import com.mysql.jdbc.Driver;
/**
 * @program: myClassCode
 * @description: jabc utils and extract some duplicate codes
 * @author: Keyu Li
 * @create: 2021-10-16 11:50
 **/

public class JDBCUtils {
    //从配置文件提取参数，并放在静态代码块中
    private static String userName;
    private static String password;
    private static String url;
    private static String driverClassName;

    static {
        try {
            Properties properties = new Properties();
            properties.load(new InputStreamReader(new FileInputStream("config/druid.properties"), "utf-8"));
            userName=properties.getProperty("username");
            password=properties.getProperty("password");
            url=properties.getProperty("url");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    //获取连接
    public static Connection getConnection(){
//        Connection connection=null;
//        try {
//            // 1.加载驱动
////            Class.forName("com.mysql.jdbc.Driver");
//            DriverManager.registerDriver(new Driver());
//            // 2.获取连接，直接在代码中赋值称为魔法值
//            connection = DriverManager.getConnection(furl, userName, password);
//        } catch (SQLException throwables) {
//            throwables.printStackTrace();
//        }
//        return connection;
        try {
            return DriverManager.getConnection(url,userName,password);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            return null;
        }
    }

    //关闭资源
    public static void closeSources(Connection c, Statement s, ResultSet r){
        //防止java指令重排序：
        // 1.volatile：内存可见性；控制指令重排序
        // 2.使用try...finally严格控制执行先后顺序，
        try {
            if (r!=null) r.close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            try {
                if (s!=null) s.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }finally {
                try {
                    if (c!=null) c.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }
    }
}
